<template>
	<view class="random-call-container">
		<!-- 背景装饰元素 -->
		<view class="bg-circle bg-circle-1"></view>
		<view class="bg-circle bg-circle-2"></view>

		<!-- 标题栏 -->
		<view class="header">
			<text class="title">随机点名</text>
			<text class="subtitle">二年级课堂点名系统</text>
		</view>

		<audio id="nameAudio" :src="`http://127.0.0.1:8080/getSounds?text=${audioText}`" autoplay></audio>
		<!-- 点名区域 -->
		<view class="call-area">
			<!-- 学生头像动画 -->
			<view class="student-avatar-container" :class="{ 'rolling': isRolling }">
				<image v-if="selectedStudent" class="student-avatar" :src="selectedStudent.aver || '/static/aver1.jpg'"
					mode="aspectFill"></image>
				<view v-else class="default-avatar">
					<uni-icons type="person" size="60" color="#fff"></uni-icons>
				</view>
			</view>

			<!-- 学生信息 -->
			<view class="student-info" v-if="selectedStudent">
				<text class="student-name">{{selectedStudent.studentName}}</text>
				<view class="student-meta">
				</view>
			</view>
			<view class="placeholder" v-else>
				<text>点击开始按钮随机选择学生</text>
			</view>

			<!-- 控制按钮 -->
			<view class="control-buttons">
				<button class="action-btn start-btn" :disabled="!students.length || isRolling" @click="startRolling">
					{{ isRolling ? '随机选择中...' : '开始点名' }}
				</button>
				<button class="action-btn reset-btn" :disabled="!selectedStudent" @click="showResetConfirm">
					重新选择
				</button>
			</view>
			<!-- 在call-area内添加滑块，放在控制按钮上方 -->
			<view class="slider-container">
				<text class="slider-label">声音甜度调节</text>
				<slider class="sweetness-slider" min="1" max="10" step="1" :value="voiceSweetness"
					@change="onSweetnessChange" activeColor="#667eea" backgroundColor="#e4e8f0" block-size="20"
					block-color="#764ba2" show-value />
				<view class="slider-tips">
					<text>御姐</text>
					<text>甜美</text>
				</view>
			</view>
		</view>

		<!-- 已选学生记录 -->
		<view class="selected-records" v-if="sortedSelectedRecords.length">
			<view class="section-title">
				<text>已选学生记录 (按选择次数排序)</text>
			</view>
			<view class="records-grid">
				<view class="record-card" v-for="(record, index) in sortedSelectedRecords" :key="index">
					<image class="record-avatar" :src="record.student.aver || '/static/aver1.jpg'"></image>
					<view class="record-info">
						<text class="record-name">{{record.student.studentName}}</text>
						<view class="record-meta">
							<text class="meta-item">被选次数: {{record.count}}</text>
							<text class="meta-item">最近选择: {{formatTime(record.lastSelected)}}</text>
						</view>
					</view>
					<view class="record-badge" :class="getBadgeClass(index)">
						{{index + 1}}
					</view>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<uni-load-more v-if="loading" status="loading"></uni-load-more>

		<!-- 确认弹窗 -->
		<uni-popup ref="resetPopup" type="dialog">
			<uni-popup-dialog mode="base" title="确认操作" content="确定要清空所有选择记录吗？" :duration="2000"
				@confirm="resetAllRecords" @close="closeResetDialog"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				grade: '',
				students: [],
				selectedStudent: null,
				isRolling: false,
				loading: true,
				voiceSweetness: 5, // 默认中等甜度
				audioText: '请选择学生',
				selectedRecords: [] // 格式: {student: {}, count: number, lastSelected: timestamp}
			}
		},
		computed: {
			// 按选择次数从大到小排序的记录
			sortedSelectedRecords() {
				return [...this.selectedRecords].sort((a, b) => b.count - a.count);
			}
		},
		onLoad(option) {

			this.grade = option.grade;
			this.fetchStudents();
			this.loadSweetnessSetting();
			this.playSuccessSound("下面开始点名");
		},
		methods: {
			async loadSweetnessSetting() {
				try {
					const savedSweetness = await uni.getStorageSync('voiceSweetness');
					if (savedSweetness) {
						this.voiceSweetness = parseInt(savedSweetness);
					}
				} catch (e) {
					console.log('加载甜度设置失败', e);
				}
			},
			async saveSweetnessSetting() {
				try {
					await uni.setStorageSync('voiceSweetness', this.voiceSweetness.toString());
				} catch (e) {
					console.log('保存甜度设置失败', e);
				}
			},
			onSweetnessChange(e) {
				this.voiceSweetness = e.detail.value;
				this.saveSweetnessSetting(); // 保存设置
			},

			playSuccessSound(text) {
				const audio = uni.createInnerAudioContext();
				audio.src = globalVariable + `/getSounds?text=${text}&pit=${this.voiceSweetness}`;
				audio.play();
			},
			fetchStudents() {
				this.loading = true;
				uni.request({
					url: globalVariable + "/getStudentsByGrade?grade=" + this.grade,
					success: (res) => {
						if (res.data.status === 1) {
							this.students = res.data.data;
						}
					},
					complete: () => {
						this.loading = false;
					}
				});
			},

			startRolling() {
				if (this.isRolling || !this.students.length) return;

				this.isRolling = true;
				let counter = 0;
				const totalRolls = 20 + Math.floor(Math.random() * 10);

				this.rollInterval = setInterval(() => {
					counter++;
					const randomIndex = Math.floor(Math.random() * this.students.length);
					this.selectedStudent = this.students[randomIndex];

					if (counter >= totalRolls) {
						clearInterval(this.rollInterval);
						this.isRolling = false;
						this.addToSelectedRecords();
						this.playSuccessSound(`恭喜${this.selectedStudent.studentName}同学被选中`);
					}
				}, 100);
			},

			showResetConfirm() {
				this.$refs.resetPopup.open();
			},

			closeResetDialog() {
				this.$refs.resetPopup.close();
			},

			resetAllRecords() {
				this.playSuccessSound("重新选择学生");
				this.selectedStudent = null;
				this.selectedRecords = [];
				uni.showToast({
					title: '已清空所有记录',
					icon: 'success'
				});
			},

			addToSelectedRecords() {
				if (!this.selectedStudent) return;

				const now = new Date();
				const existingIndex = this.selectedRecords.findIndex(
					r => r.student.userId === this.selectedStudent.userId
				);

				if (existingIndex >= 0) {
					// 更新已有记录
					this.selectedRecords[existingIndex].count++;
					this.selectedRecords[existingIndex].lastSelected = now;
				} else {
					// 添加新记录
					this.selectedRecords.unshift({
						student: this.selectedStudent,
						count: 1,
						lastSelected: now
					});
				}
			},



			formatTime(time) {
				if (!time) return '';
				const date = new Date(time);
				return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
			},

			getBadgeClass(index) {
				if (index === 0) return 'badge-gold';
				if (index === 1) return 'badge-silver';
				if (index === 2) return 'badge-bronze';
				return 'badge-normal';
			}
		}
	}
</script>

<style scoped>
	.slider-container {
		margin: 40rpx 0;
		padding: 0 20rpx;
	}

	.slider-label {
		display: block;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 20rpx;
		text-align: center;
	}

	.sweetness-slider {
		margin: 20rpx 0;
	}

	.slider-tips {
		display: flex;
		justify-content: space-between;
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #999;
	}

	.random-call-container {
		position: relative;
		min-height: 100vh;
		padding: 30rpx;
		/* background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%); */
		overflow: hidden;
	}

	/* 背景装饰 */
	.bg-circle {
		position: absolute;
		border-radius: 50%;
		background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
		filter: blur(60rpx);
		z-index: 0;
	}

	.bg-circle-1 {
		width: 400rpx;
		height: 400rpx;
		top: -100rpx;
		left: -100rpx;
	}

	.bg-circle-2 {
		width: 600rpx;
		height: 600rpx;
		bottom: -200rpx;
		right: -200rpx;
		background: linear-gradient(135deg, rgba(255, 167, 38, 0.1) 0%, rgba(255, 77, 79, 0.1) 100%);
	}

	/* 标题 */
	.header {
		position: relative;
		z-index: 1;
		margin-bottom: 40rpx;
		text-align: center;
	}

	.title {
		display: block;
		font-size: 48rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}

	.subtitle {
		font-size: 28rpx;
		color: #666;
	}

	/* 点名区域 */
	.call-area {
		position: relative;
		z-index: 1;
		background: rgba(255, 255, 255, 0.8);
		backdrop-filter: blur(10px);
		border-radius: 30rpx;
		padding: 40rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.08);
		text-align: center;
	}

	.student-avatar-container {
		width: 200rpx;
		height: 200rpx;
		margin: 0 auto 30rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		transition: transform 0.3s ease;
		box-shadow: 0 10rpx 30rpx rgba(102, 126, 234, 0.3);
	}

	.student-avatar-container.rolling {
		animation: rolling 0.1s linear infinite;
	}

	@keyframes rolling {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.student-avatar {
		width: 180rpx;
		height: 180rpx;
		border-radius: 50%;
		border: 4rpx solid #fff;
	}

	.default-avatar {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.student-info {
		margin-bottom: 30rpx;
	}

	.student-name {
		display: block;
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 16rpx;
	}

	.student-meta {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.meta-item {
		font-size: 26rpx;
		color: #666;
	}

	.placeholder {
		height: 120rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999;
	}

	/* 控制按钮 */
	.control-buttons {
		display: flex;
		justify-content: center;
		gap: 20rpx;
	}

	.action-btn {
		flex: 1;
		max-width: 300rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		border: none;
		transition: all 0.3s ease;
	}

	.start-btn {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
	}

	.start-btn:active {
		transform: scale(0.98);
		opacity: 0.9;
	}

	.start-btn[disabled] {
		background: linear-gradient(135deg, #cccccc 0%, #999999 100%);
	}

	.reset-btn {
		background: rgba(255, 255, 255, 0.8);
		border: 1px solid #ddd;
		color: #666;
	}

	.reset-btn:active {
		background: rgba(255, 255, 255, 0.6);
	}

	.reset-btn[disabled] {
		opacity: 0.5;
	}

	/* 已选学生记录 */
	.selected-records {
		position: relative;
		z-index: 1;
		margin-top: 40rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 24rpx;
		padding-left: 20rpx;
		position: relative;
	}

	.section-title::before {
		content: '';
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		height: 30rpx;
		width: 8rpx;
		background: linear-gradient(to bottom, #667eea, #764ba2);
		border-radius: 4rpx;
	}

	.records-grid {
		display: grid;
		grid-template-columns: 1fr;
		gap: 20rpx;
	}

	.record-card {
		background: rgba(255, 255, 255, 0.8);
		backdrop-filter: blur(10px);
		border-radius: 20rpx;
		padding: 24rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.03);
		transition: all 0.3s ease;
		position: relative;
	}

	.record-card:active {
		transform: translateY(4rpx);
	}

	.record-avatar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		border: 2rpx solid #eee;
		margin-right: 20rpx;
	}

	.record-info {
		flex: 1;
	}

	.record-name {
		display: block;
		font-size: 30rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 12rpx;
	}

	.record-meta {
		display: flex;
		flex-direction: column;
		gap: 6rpx;
	}

	.meta-item {
		font-size: 24rpx;
		color: #666;
	}

	.record-badge {
		position: absolute;
		right: 20rpx;
		top: 20rpx;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 22rpx;
		font-weight: bold;
		color: white;
	}

	.badge-gold {
		background: linear-gradient(135deg, #FFD700, #D4AF37);
		box-shadow: 0 4rpx 12rpx rgba(255, 215, 0, 0.3);
	}

	.badge-silver {
		background: linear-gradient(135deg, #C0C0C0, #A8A8A8);
		box-shadow: 0 4rpx 12rpx rgba(192, 192, 192, 0.3);
	}

	.badge-bronze {
		background: linear-gradient(135deg, #CD7F32, #B87333);
		box-shadow: 0 4rpx 12rpx rgba(205, 127, 50, 0.3);
	}

	.badge-normal {
		background: linear-gradient(135deg, #667eea, #764ba2);
		box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
	}
</style>